﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace T03ChatServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public Socket server = null;
        public bool isListen = true;
        public Dictionary<string, Socket> clientList = null;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            if (server == null)
            {
                isListen = true;
                clientList = new Dictionary<string, Socket>();
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                IPEndPoint iep = new IPEndPoint(ip, 13000);
                server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                server.Bind(iep);
                server.Listen(100);
                Thread thread = new Thread(ListenStart);
                thread.IsBackground = true;
                thread.Start();
                TxtMsg.Dispatcher.BeginInvoke(new Action(() => { TxtMsg.Text += "服务启动...\r\n"; }));
            }
        }
        public void ListenStart()
        {
            Socket clientScoket = default(Socket);
            try
            {
                while (isListen)
                {
                    string datafromclient = null;
                    byte[] buff = new byte[4096]; 
                    clientScoket = server.Accept(); 
                    int len = clientScoket.Receive(buff); 
                    if (len > 0)
                    {
                        datafromclient = Encoding.UTF8.GetString(buff, 0, len);
                        int index = datafromclient.LastIndexOf("$");
                        if (index > -1)
                        { 
                            datafromclient = datafromclient.Substring(0, index);
                            if (!clientList.ContainsKey(datafromclient))
                            {
                                clientList.Add(datafromclient, clientScoket);
                                BroadCast.BroadMessage(datafromclient + "加入", "", clientList, BroadCast.SERVER_MSG);
                                new HandleClient().StartListen(clientScoket, datafromclient, clientList); 
                                TxtMsg.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    TxtMsg.Text += datafromclient + "加入" + "\r\n";
                                }));
                            }
                            else
                            {
                                clientScoket.Send(Encoding.UTF8.GetBytes("#" + datafromclient + "#"));
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (clientScoket != null && !clientScoket.Connected)
                {
                    clientScoket.Close();
                    clientScoket = null;
                }
                Debug.WriteLine(e.ToString());
            }


        }
        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            if (server != null)
            {
                BroadCast.BroadMessage("服务器即将关闭...", "", clientList, BroadCast.SERVER_MSG);
                //关闭所有客户端连接
                foreach (var item in clientList.Values)
                {
                    item.Close();
                }
                //清空字典
                clientList.Clear();
                server.Close();
                server = null;
                //停止监听线程
                isListen = false;
                TxtMsg.Text += "服务停止...\r\n";
            }
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            isListen = false;
            if (server != null)
            {
                //关闭所有客户端连接
                foreach (var item in clientList.Values)
                {
                    item.Close();
                }
                //清空字典
                clientList.Clear();
                server.Close();
                server = null;
            }
        }



    }
}
